package cn.wolfcode.crm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.mapper.EmployeeRoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
@Service
public class EmployeeServiceImpl implements IEmployeeService{

	@Autowired
	private EmployeeMapper employeeMapper;
	
	@Autowired
	private EmployeeRoleMapper employeeRoleMapper;

	@Override
	public void saveOrUpdate(Employee entity) {
		if (entity.getId() == null) {
			employeeMapper.insert(entity);
			if (entity.getIds() != null && entity.getIds().length > 0) {
				employeeRoleMapper.insertEmployeeRole(entity.getId(), entity.getIds());
			}
		}else {
			employeeMapper.update(entity);
			employeeRoleMapper.removeByEmployeeId(entity.getId());
			if (!entity.isAdmin() && entity.getIds() != null && entity.getIds().length > 0) {
				employeeRoleMapper.insertEmployeeRole(entity.getId(), entity.getIds());
			}
		}
		
	}

	@Override
	public String delete(Long id) {
		String message = "删除成功";
		if (employeeRoleMapper.countEmployeeRoleByEmployeeId(id) > 0) {
			message = "删除失败，用户有被角色关联，不能删除";
		}else {
			employeeMapper.delete(id);
		}
		return message;
	}

	@Override
	public Employee get(Long id) {
		return employeeMapper.selectRoleByEmployeeId(id);
	}

	@Override
	public PageInfo<Employee> list(QueryObject qo) { 
		PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
//		List<Employee> list = employeeMapper.selectAll();
		List<Employee> list = employeeMapper.selectForList(qo);
		return new PageInfo<>(list);
	}

	@Override
	public List<Employee> querySellersForNotId(Long id) {
		return employeeMapper.querySellersForNotId(id);
	}

}
